var $layui = layui.jquery;
// ----------------------------------------------------------------------
// <summary>
// 扩展String类，添加Format静态方法，模仿C#中的String.Format方法
// </summary>
// <returns>str</returns>
// ----------------------------------------------------------------------
if (!String.format) {
    String.format = function () {
        if (arguments.length == 0) {
            return null;
        }
        var str = arguments[0];
        if (arguments[1] instanceof Array) {
            var arr = arguments[1];
            for (var i = 0; i < arr.length; i++) {
                var re = new RegExp('\\{' + i + '\\}', 'gm');
                str = str.replace(re, arr[i]);
            }
        } else {
            for (var i = 1; i < arguments.length; i++) {
                var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
                str = str.replace(re, arguments[i]);

            }
        }
        return str;
    }
}

/**
 * 限制指定输入框元素只能输入非负整数字
 * @param inputElm 输入框元素
 */
function inputInteger(inputElm){
    inputFormat(inputElm,/\D/g,"");
}
/**
 * 输入框格式化，限制输入框不能输入的字符
 * @param inputElm 输入框元素
 * @param reg 需要替换字符串的正则表达式
 * @param toValue 将满足reg正则的字符替换为toValue，缺省值 ''
 */
function inputFormat(inputElm,reg,toValue){
    toValue =  toValue || '';
    var exclusive = [8,35,36,37,38,39,40,48];//排除部分功能跟按键
    var $inputElm =  $(inputElm);
    $inputElm.on("keyup",function(e){
        var oldVal = e.target.value;
        if(oldVal && (exclusive.indexOf(e.keyCode) == -1)) {
            e.target.value=oldVal.replace(reg,toValue)
        }
    });
    $inputElm.on("blur",function(e){
        e.target.value= e.target.value.replace(reg,toValue)
    });
}

/**
 * 限制指定输入框元素只能输入非负数字，保留两位小数
 * @param inputElm 输入框元素
 */
function inputDecimal(inputElm){
    var exclusive = [8,35,36,37,38,39,40,48];//排除部分功能跟按键
    $(inputElm).on("keyup",function(e){
        if(exclusive.indexOf(e.keyCode) == -1) {
            inputDecimalFormat(e.target)
        }
    });
    $(inputElm).on("blur",function(e){
        if(exclusive.indexOf(e.keyCode) == -1) {
            overDecimalFormat(e.target)
        }
    });
}
/**
 * Created by laotou on 2016/11/3.
 */
/**
 * 强制输入框只能输入纯数字
 * 实时动态强制更改用户录入
 * arg1 inputObject
 **/
function inputIntegerFormat(th){
    th.value=th.value.replace(/\D/g,'')
}
/**
 * 强制输入框只能输入正数，最多两位数字
 * 主要用于金额输入
 * 实时动态强制更改用户录入
 * arg1 inputObject
 **/
function inputDecimalFormat(th){
    var regStrs = [
        [/^0(\d+)$/g, '$1'], //禁止录入整数部分两位以上，但首位为0
        [/[^\d\.]+$/g, ''], //禁止录入任何非数字和点
        [/\.(\d?)\.+/g, '.$1'], //禁止录入两个以上的点
        [/^(\d+\.\d{2}).+/g, '$1'], //禁止录入小数点后两位以上
        [/^\./g, ''] //禁止录入第一位是小数点
    ];
    for(var i=0; i<regStrs.length; i++){
        var reg = regStrs[i][0];
        th.value = th.value.replace(reg, regStrs[i][1]);
    }
}
/**
 * 强制输入框只能输入正数，最多两位数字
 *
 * 录入完成后，输入模式失去焦点后对录入进行判断并强制更改，并对小数点进行0补全
 * arg1 inputObject
 *
 **/
function overDecimalFormat(th){
    var v = th.value;
    if(v === ''){
        //v = '0.00';
    }else if(v.match(/^0*$/g)){
        v = '0.00';
    }else if(v === '0.'){
        v = '0.00';
    }else if(/^0+\d+\.?\d*.*$/.test(v)){
        v = v.replace(/^0+(\d+\.?\d*).*$/, '$1');
        //v = inp.getRightPriceFormat(v).val;
    }else if(/^0\.\d$/.test(v)){
        v = v + '0';
    }else if(!/^\d+\.\d{2}$/.test(v)){
        if(/^\d+\.\d{2}.+/.test(v)){
            v = v.replace(/^(\d+\.\d{2}).*$/, '$1');
        }else if(/^\d+$/.test(v)){
            v = v + '.00';
        }else if(/^\d+\.$/.test(v)){
            v = v + '00';
        }else if(/^\d+\.\d$/.test(v)){
            v = v + '0';
        }else if(/^[^\d]+\d+\.?\d*$/.test(v)){
            v = v.replace(/^[^\d]+(\d+\.?\d*)$/, '$1');
        }else if(/\d+/.test(v)){
            v = v.replace(/^[^\d]*(\d+\.?\d*).*$/, '$1');
            ty = false;
        }else if(/^0+\d+\.?\d*$/.test(v)){
            v = v.replace(/^0+(\d+\.?\d*)$/, '$1');
            ty = false;
        }else{
            v = '0.00';
        }
    }
    th.value = v;
}

function layerAlert(text){
    layui.layer.alert(text,{
        title: '提示框',
        icon:0
    });
}
function layerAlertParent(text){
    layui.layer.alert(text,{
        title: '提示框',
        icon:0
    });
}
function overDecimalFormat(th){
    var v = th.value;
    if(v === ''){
        //v = '0.00';
    }else if(v.match(/^0*$/g)){
        v = '0.00';
    }else if(v === '0.'){
        v = '0.00';
    }else if(/^0+\d+\.?\d*.*$/.test(v)){
        v = v.replace(/^0+(\d+\.?\d*).*$/, '$1');
        //v = inp.getRightPriceFormat(v).val;
    }else if(/^0\.\d$/.test(v)){
        v = v + '0';
    }else if(!/^\d+\.\d{2}$/.test(v)){
        if(/^\d+\.\d{2}.+/.test(v)){
            v = v.replace(/^(\d+\.\d{2}).*$/, '$1');
        }else if(/^\d+$/.test(v)){
            v = v + '.00';
        }else if(/^\d+\.$/.test(v)){
            v = v + '00';
        }else if(/^\d+\.\d$/.test(v)){
            v = v + '0';
        }else if(/^[^\d]+\d+\.?\d*$/.test(v)){
            v = v.replace(/^[^\d]+(\d+\.?\d*)$/, '$1');
        }else if(/\d+/.test(v)){
            v = v.replace(/^[^\d]*(\d+\.?\d*).*$/, '$1');
            ty = false;
        }else if(/^0+\d+\.?\d*$/.test(v)){
            v = v.replace(/^0+(\d+\.?\d*)$/, '$1');
            ty = false;
        }else{
            v = '0.00';
        }
    }
    th.value = v;
}
function inputDecimalFormat(th){
    var regStrs = [
        [/^0(\d+)$/g, '$1'], //禁止录入整数部分两位以上，但首位为0
        [/[^\d\.]+$/g, ''], //禁止录入任何非数字和点
        [/\.(\d?)\.+/g, '.$1'], //禁止录入两个以上的点
        [/^(\d+\.\d{2}).+/g, '$1'], //禁止录入小数点后两位以上
        [/^\./g, ''] //禁止录入第一位是小数点
    ];
    for(i=0; i<regStrs.length; i++){
        var reg = regStrs[i][0];
        th.value = th.value.replace(reg, regStrs[i][1]);
    }
}
/**
 * 根据请求地址动态获取下拉框元素
 * @param selectEleId 下拉框元素ID
 * @param reqUrl ajax请求地址
 * @param textfield 下拉框文本显示字段名
 * @param valuefiled 下拉框选中的值对应的字段名
 * @param defaultSelectedByValue 默认选中项
 * @param endFn 加载完成后执行的函数
 */
function loadSelectOption(selectEleId,reqUrl,textfield,valuefiled,defaultSelectedByValue,endFn){
    if(reqUrl.length == 0) throw "request is required";
    var control = $('#' + selectEleId);
    control.find("option").remove();
    //control.prepend("<option value=''>请选择</option>");
    $.ajax({
        //以application/json的方式传输数据，服务端通过@RequestBody注解去接收
        contentType: "application/json",
        type: "GET",//要显示指明提交类型
        url: reqUrl,
        success: function(json){
            if(json){
                var selectVals=new Array();
                $.each(json,function(n,obj){
                    var option = new Option(eval("obj."+textfield),eval("obj."+valuefiled));
                    if(eval("obj.isSelected")==1)option.disabled=true;
                    control[0].options.add(option);
                    if(eval("obj.isDisabled")==1)selectVals.push(eval("obj."+valuefiled));
                });
                if(defaultSelectedByValue!=undefined){
                    //根据value设置默认选中项
                    control.val(defaultSelectedByValue);
                }
                if(endFn != undefined){
                    endFn(json);
                }
                if(selectVals !=undefined && !selectVals && selectVals.length>0)control.val(selectVals);
            }else{
                endFn();
            }
        }
    });
}

function loadSelect(form, selectEleId, url, endFn, def, text, value){
    if(!text) text = 'name';
    if(!value) value = 'id';
    var control = $('#' + selectEleId);
    control.find("option").remove();
    control.prepend("<option value=''>请选择</option>");
    $.ajax({
        url: url,
        success: function(data){
            $.each(data, function(n, o){
                var selected = '';
                if(def && def==eval("o."+value)) selected = 'selected';
                control.append('<option value="'+eval("o."+value)+'" '+selected+'>'+eval("o."+text)+'</option>');
            });
            form.render('select');
            if(typeof endFn == 'function') endFn(data);
        }
    });
}

function loadSelect2(form, selectEleId, url, endFn, optext, def , text, value){
    if(!text) text = 'name';
    if(!value) value = 'id';
    var control = $('#' + selectEleId);
    control.find("option").remove();
    control.prepend("<option value=''>"+optext+"</option>");
    $.ajax({
        url: url,
        success: function(data){
            $.each(data, function(n, o){
                var selected = '';
                if(def && def==eval("o."+value)) selected = 'selected';
                if(def==0 && n==0) selected = 'selected';
                control.append('<option value="'+eval("o."+value)+'" '+selected+'>'+eval("o."+text)+'</option>');
            });
            form.render('select');
            if(typeof endFn == 'function') endFn(data);
        }
    });
}

function loadSelect3(control, url, parameters, text, value, endFn, def){
    if(!text) text = 'name';
    if(!value) value = 'id';
    control.find("option").remove();
    control.prepend("<option value=''>直接选择或搜索选择</option>");
    $.ajax({
        url: url,
        data: parameters,
        success: function(data){
            $.each(data, function(n, o){
                var selected = '';
                if(def && def==eval("o."+value)) selected = 'selected';
                control.append('<option value="'+eval("o."+value)+'" '+selected+'>'+eval("o."+text)+'</option>');
            });
            if(typeof endFn == 'function') endFn(data);
        }
    });
}


function loadSelectValFirst(form, selectEleId, url, endFn, def, text, value){
    if(!text) text = 'name';
    if(!value) value = 'id';
    var control = $('#' + selectEleId);
    control.find("option").remove();
    $.ajax({
        url: url,
        success: function(data){
            $.each(data, function(n, o){
                var selected = '';
                if(def && def==eval("o."+value)) selected = 'selected';
                control.append('<option value="'+eval("o."+value)+'" '+selected+'>'+eval("o."+text)+'</option>');
            });
            if(data.length == 0){
                control.prepend("<option value=''>请选择</option>");
            }
            form.render('select');
            if(typeof endFn == 'function') endFn(data);
        }
    });
}


var timeHHmm = ['00:00','00:30','01:00','01:30','02:00','02:30','03:00','03:30','04:00','04:30','05:00','05:30','06:00','06:30','07:00','07:30','08:00','08:30','09:00','09:30',
    '10:00','10:30','11:00','11:30','12:00','12:30','13:00','13:30','14:00','14:30','15:00','15:30','16:00','16:30','17:00','17:30','18:00','18:30','19:00','19:30',
    '20:00','20:30','21:00','21:30','22:00','22:30','23:00','23:30'];
function loadTimeHHmm(form, str){
    $(str).find("option").remove();
    $.each(timeHHmm, function(n, obj){
        $(str).append('<option value="'+obj+'">'+obj+'</option>');
    });
    form.render('select');
}
function loadTimeHHmm2(str){
    $(str).find("option").remove();
    $(str).each(function(){
        var $this = $(this),value = $this.attr('value');
        $.each(timeHHmm, function(n, obj){
            var str = '';
            if(value == obj){
                str = 'selected';
            }
            $this.append('<option value="'+obj+'" '+str+'>'+obj+'</option>');
        });
    });

}
function stopPropagation(str){
    $(str).on('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
    });
}
function stopPropagation2(str1, str2){
    $(str1).on('click', str2, function(e) {
        e.preventDefault();
        e.stopPropagation();
    });
}
function documentModal(endFn){
    $(document).on('click.off.modal', endFn);
}
function msg(tstr, icon){
    if(!icon)icon=2;
    layer.msg(tstr,{icon: icon, time: 2000, closeBtn: 1, skin: 'lm-tm'});
}
function toggleClass(str1, str2){
    $(str1).on('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        $(str2).toggleClass('hide');
    });
}
function loadData(jsonStr,formId){
    var key,value,arr;
    var formObj = formId ? $("#"+formId):$("body");
    for(key in jsonStr){
        value = jsonStr[key];
        if(typeof value == 'object'){
            loadData(value)
        }else{
            formObj.find("[name='"+key+"'],[name='"+key+"[]']").each(function(){
                var tagName = $(this)[0].tagName;
                var type = $(this).attr('type');
                if(tagName=='INPUT'){
                    if(type=='radio'){
                        $(this).prop('checked',$(this).val()==value);
                    }else if(type=='checkbox'){
                        arr = value.split(',');
                        for(var i =0;i<arr.length;i++){
                            if($(this).val()==arr[i]){
                                $(this).attr('checked',true);
                                break;
                            }
                        }
                    }else{
                        if($(this).hasClass('layui-time')){
                            value = new Date(value).toString('yyyy-MM-dd');
                        }
                        $(this).val(value);
                    }
                }else if(tagName=='SELECT'){
                    $(this).val(value);
                }else if(tagName=='TEXTAREA'){
                    $(this).val(value);
                }else if(tagName=='LABEL'){
                    $(this).html(value);
                }
            });
        }
    }
}

/**
 * 填充Form表单数据
 * @param jsonStr
 * @param formId 要填充的表单id,如果不传 则对body内的所哟出入框填充
 */
function loadDataOfForm(jsonStr,formId){
    var obj =jsonStr;
    var key,value,tagName,type,arr;
    var formObj = formId ? $("#"+formId):$("body");
    for(var x in obj){
        key = x;
        value = obj[x];

        formObj.find("[name='"+key+"'],[name='"+key+"[]']").each(function(){
            tagName = $(this)[0].tagName;
            type = $(this).attr('type');
            if(tagName=='INPUT'){
                if(type=='radio'){
                    if($(this).val()==value){
                        $(this).iCheck('check');
                    }else{
                        $(this).iCheck('uncheck');
                    }
                }else if(type=='checkbox'){
                    arr = value.split(',');
                    for(var i =0;i<arr.length;i++){
                        if($(this).val()==arr[i]){
                            $(this).iCheck('check');
                            break;
                        }
                    }
                }else{
                    $(this).val(value);
                }
            }else if(tagName=='SELECT' || tagName=='TEXTAREA'){
                $(this).val(value).trigger("change");
                //$(this).val(value);
            }

        });
    }
}
function nsHide(str){
    $(str).addClass('hide');
}
function nsShow(str){
    $(str).removeClass('hide');
}
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}
function getQueryString2(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = decodeURI(window.location.search).substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}
function getObjValById(id){
    var value = $("#"+id).val();
    if(value != null){
        value = value.trim();
    }else{
        value = '';
    }
    return value;
}
function getObjValByIdParent(id){
    var value = $("#"+id).val();
    if(value != null){
        value = value.trim();
    }else{
        value = '';
    }
    return value;
}
function getObjValByName(name, type){
    var $obj = getObjByName(name, type);
    var elmType = $($obj).attr("type");
    if(elmType == 'radio'){
        return $(type+":checked[name='"+name+"']").val();
    }
    if(elmType == 'checkbox'){
        return $(type+":checked[name='"+name+"']").val();
    }
    return $obj.val();
}
function getObjByName(name, type){
    return $(type+"[name='"+name+"']");
}
function toggleClass3(str, str1, str2){
    $(str).on('click', str1, function(e) {
        e.preventDefault();
        e.stopPropagation();
        $(str1).parents('.layui-input-block').find(str2).addClass('hide');
        $(this).parents('.layui-input-block').find(str2).toggleClass('hide');
    });
}
function toggleClass2(str1, str2){
    $(str1).on('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        $(str1).parents('.layui-input-block').find(str2).addClass('hide');
        $(this).parents('.layui-input-block').find(str2).toggleClass('hide');
    });
}
function fixed_note_toolbar(){
    $(document).scroll(function(){
        var top = document.getElementsByClassName("note-editor")[0].getBoundingClientRect().top; //元素顶端到可见区域顶端的距离
        if(top<=60){
            $(".note-toolbar").css({
                "position": "fixed",
                "top": "60px",
                "z-index": "99",
                "width": "936px"
            });
        }else{
            $(".note-toolbar").removeAttr("style");
        }
    });
}
Date.prototype.toString=function(format,loc){
    var time={};
    time.Year=this.getFullYear();
    time.TYear=(""+time.Year).substr(2);
    time.Month=this.getMonth()+1;
    time.TMonth=time.Month<10?"0"+time.Month:time.Month;
    time.Day=this.getDate();
    time.TDay=time.Day<10?"0"+time.Day:time.Day;
    time.Hour=this.getHours();
    time.THour=time.Hour<10?"0"+time.Hour:time.Hour;
    time.hour=time.Hour<13?time.Hour:time.Hour-12;
    time.Thour=time.hour<10?"0"+time.hour:time.hour;
    time.Minute=this.getMinutes();
    time.TMinute=time.Minute<10?"0"+time.Minute:time.Minute;
    time.Second=this.getSeconds();
    time.TSecond=time.Second<10?"0"+time.Second:time.Second;
    time.Millisecond=this.getMilliseconds();
    time.Week=this.getDay();

    var MMMArrEn=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
    var MMMArr=["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"];
    var WeekArrEn=["Sun","Mon","Tue","Web","Thu","Fri","Sat"];
    var WeekArr=["星期日","星期一","星期二","星期三","星期四","星期五","星期六"];

    var oNumber=time.Millisecond/1000;

    if(format!=undefined && format.replace(/\s/g,"").length>0){
        if(loc!=undefined && loc =="en"){
            MMMArr=MMMArrEn.slice(0);
            WeekArr=WeekArrEn.slice(0);
        }
        format=format
            .replace(/yyyy/ig,time.Year)
            .replace(/yyy/ig,time.Year)
            .replace(/yy/ig,time.TYear)
            .replace(/y/ig,time.TYear)
            .replace(/MMM/g,MMMArr[time.Month-1])
            .replace(/MM/g,time.TMonth)
            .replace(/M/g,time.Month)
            .replace(/dd/ig,time.TDay)
            .replace(/d/ig,time.Day)
            .replace(/HH/g,time.THour)
            .replace(/H/g,time.Hour)
            .replace(/hh/g,time.Thour)
            .replace(/h/g,time.hour)
            .replace(/mm/g,time.TMinute)
            .replace(/m/g,time.Minute)
            .replace(/ss/ig,time.TSecond)
            .replace(/s/ig,time.Second)
            .replace(/fff/ig,time.Millisecond)
            .replace(/ff/ig,oNumber.toFixed(2)*100)
            .replace(/f/ig,oNumber.toFixed(1)*10)
            .replace(/EEE/g,WeekArr[time.Week]);
    }
    else{
        format=time.Year+"-"+time.Month+"-"+time.Day+" "+time.Hour+":"+time.Minute+":"+time.Second;
    }
    return format;
};

/**
 * 导出excel
 *  无弹窗、选列
 * @param url 导出地址
 * @param columns 导出的列 格式为json数组，每一项必须包含field（属性）和title(列名):
 *       [{field: 'nickname',title: '昵称'},{field: 'userName',title: '姓名'}]
 * @param jsonData 要传的其它参数 json格式
 * @param afterExport 导出后执行的方法
 */
function exportExcel(url ,columns,jsonData , afterExport) {
    if(!jsonData) jsonData = {};
    jsonData.columns = JSON.stringify(columns);
    postRequestDownload(url,jsonData,afterExport);
}
/**
 * 导出excel
 * @param url 导出地址
 * @param jsonData 要传的其它参数 json格式
 * @param afterExport 导出后执行的方法
 */
function exportExcelNoCol(url,jsonData , afterExport) {
    if(!jsonData) jsonData = {};
    postRequestDownload(url,jsonData,afterExport);
}

/**
 *通过post请求下载（导出）文件，
 * @param url 下载地址
 * @param jsonData 请求参数，任意参数，只要第一级为json形式即可
 * 如 {id:"dd",name:"tom",houseId:["xxx","yyy"],houseUser:{id:"bb",name:"liza"}}
 * 或 {id:"dd",name:"tom",houseId:"xxx,yyy",houseUser:"id=bb&name=lixa"}
 * 等
 * 二级以上参数形式不限，只作为一级参数的value值上传
 * @param afterDownload 导出后进行的自定义操作,在用户点击保存，浏览器弹出保存文件窗口后执行（子窗口的subWindow.onbeforeunload事件）
 * 				不管用户是否保存都会执行。
 */
function postRequestDownload(url,jsonData,afterDownload){
    //创建一个隐藏的form用来提交参数
    var $exportForm = $(String.format("<form id='exportSubmitForm' action='{0}' method='post' target='_self' style='display: none'></form>",url));
    //将所有一级参数添加到隐藏form中，所有二级以上参数作为对应一级参数 的value值
    for (var key in jsonData){
        var hidden = String.format("<input  type='hidden' name='{0}' value='{1}'/>",key,jsonData[key]);
        $exportForm.append(hidden);
    }
    $("body").append($exportForm);
    //绑定提交事件，提交后弹窗下载
    $("#exportSubmitForm").submit(function (){
        //_self 在当前窗口打开 ；_blank 加载到一个新的窗口。这是默认。修改此参数需修改隐藏form中的target属性
        var subWindow = window.open('about:blank',"_self",'height=400, width=400, top=0, left=0, toolbar=yes,depended=no, menubar=yes, scrollbars=yes, resizable=yes,location=yes, status=yes');
        //弹出保存文件窗口后执行的操作，用户自定义
        if($.isFunction(afterDownload)){
            subWindow.onbeforeunload = afterDownload;
        }
    });
    $("#exportSubmitForm").submit().remove();//提交请求，移除隐藏form
}

//手机号和座机数字正则验证
function isMobile(value){
    var isPhone = /^([0-9]{3,4}-)?[0-9]{7,8}$/;
    var isMob=/^((\+?86)|(\+86))?(13[0123456789][0-9]{8}|15[0123456789][0-9]{8}|18[023456789][0-9]{8}|147[0-9]{8}|1349[0-9]{7})$/;
    if(isMob.exec(value)||isPhone.exec(value)){
        return true;
    }else{
        return false;
    }
}
//判断用户输入的电子邮箱格式是否正确
function checkEmail(email){
    var isEmail=/^[a-zA-Z0-9_-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org)$/;

    if(isEmail.test(email)){
        return true;
    }else{
        return false;
    }
}

//验证身份证号
function isIdCard(value){
    return idCard(value);
}
var idCard = function (value) {
    if (value.length == 18 && 18 != value.length) return false;
    var number = value.toLowerCase();
    var d, sum = 0, v = '10x98765432', w = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2], a = '11,12,13,14,15,21,22,23,31,32,33,34,35,36,37,41,42,43,44,45,46,50,51,52,53,54,61,62,63,64,65,71,81,82,91';
    var re = number.match(/^(\d{2})\d{4}(((\d{2})(\d{2})(\d{2})(\d{3}))|((\d{4})(\d{2})(\d{2})(\d{3}[x\d])))$/);
    if (re == null || a.indexOf(re[1]) < 0) return false;
    if (re[2].length == 9) {
        number = number.substr(0, 6) + '19' + number.substr(6);
        d = ['19' + re[4], re[5], re[6]].join('-');
    } else d = [re[9], re[10], re[11]].join('-');
    if (!isDateTime.call(d, 'yyyy-MM-dd')) return false;
    for (var i = 0; i < 17; i++) sum += number.charAt(i) * w[i];
    return (re[2].length == 9 || number.charAt(17) == v.charAt(sum % 11));
};
var isDateTime = function (format, reObj) {
    format = format || 'yyyy-MM-dd';
    var input = this, o = {}, d = new Date();
    var f1 = format.split(/[^a-z]+/gi), f2 = input.split(/\D+/g), f3 = format.split(/[a-z]+/gi), f4 = input.split(/\d+/g);
    var len = f1.length, len1 = f3.length;
    if (len != f2.length || len1 != f4.length) return false;
    for (var i = 0; i < len1; i++) if (f3[i] != f4[i]) return false;
    for (var i = 0; i < len; i++) o[f1[i]] = f2[i];
    o.yyyy = s(o.yyyy, o.yy, d.getFullYear(), 9999, 4);
    o.MM = s(o.MM, o.M, d.getMonth() + 1, 12);
    o.dd = s(o.dd, o.d, d.getDate(), 31);
    o.hh = s(o.hh, o.h, d.getHours(), 24);
    o.mm = s(o.mm, o.m, d.getMinutes());
    o.ss = s(o.ss, o.s, d.getSeconds());
    o.ms = s(o.ms, o.ms, d.getMilliseconds(), 999, 3);
    if (o.yyyy + o.MM + o.dd + o.hh + o.mm + o.ss + o.ms < 0) return false;
    if (o.yyyy < 100) o.yyyy += (o.yyyy > 30 ? 1900 : 2000);
    d = new Date(o.yyyy, o.MM - 1, o.dd, o.hh, o.mm, o.ss, o.ms);
    var reVal = d.getFullYear() == o.yyyy && d.getMonth() + 1 == o.MM && d.getDate() == o.dd && d.getHours() == o.hh && d.getMinutes() == o.mm && d.getSeconds() == o.ss && d.getMilliseconds() == o.ms;
    return reVal && reObj ? d : reVal;
    function s(s1, s2, s3, s4, s5) {
        s4 = s4 || 60, s5 = s5 || 2;
        var reVal = s3;
        if (s1 != undefined && s1 != '' || !isNaN(s1)) reVal = s1 * 1;
        if (s2 != undefined && s2 != '' && !isNaN(s2)) reVal = s2 * 1;
        return (reVal == s1 && s1.length != s5 || reVal > s4) ? -10000 : reVal;
    }
};

function loadExcelImport(url1,url2){
    var html =
        '<div class="newseax-util-import">' +
        '<form class="layui-form newseax-util-import-form" enctype="multipart/form-data">' +
        '<div class="newseax-util-import-body">' +
        '<div class="newseax-util-import-select">' +
        '<div class="newseax-util-import-file-show">选择文件</div>' +
        '<input type="file" name="uploadFile" accept=".xls,.xlsx" class="newseax-util-import-file"/>' +
        '</div>' +
        '<div class="newseax-util-import-content">' +
        '<div class="newseax-util-import-title"></div>' +
        '<div class="newseax-util-import-title-select"></div>' +
        '</div>' +
        '</div>' +
        '</form>' +
        '</div>';
    layer.open({
        type:1,
        skin: 'newseax-util-import-layui',
        title: '导入Excel',
        area: ['960px', '680px'],
        btn: ['确认', '取消'],
        content: html,
        yes: function(index, layero){
            if(!$('.newseax-util-import-title-select').html()){
                layerAlert('请选择要导入的列');
                return false;
            }
            var objs = [];
            $('.newseax-util-import-title-select>div').each(function(n, obj){
                var eIndex = $(obj).attr('tid'),eName = $(obj).find('select').val();
                objs.push({eIndex:eIndex,eName:eName});
            });
            $('.newseax-util-import-form').ajaxSubmit({
                url: url2,
                type: 'post',
                data: {beans:JSON.stringify(objs)},
                success: function(result){
                    if(result && result.state==1){
                        layer.close(index);
                        layerAlert('导入成功');
                    }
                }
            });
            return false;
        },
        success: function(){
            layui.use('form', function(){
                var form = layui.form();
                $('.newseax-util-import-file').on('change', function(){
                    $('.newseax-util-import-form').ajaxSubmit({
                        url: url1,
                        type: 'post',
                        success: function(result){
                            if(result){
                                if(result.exceTitles){
                                    var titles = [''];
                                    $.each(result.exceTitles, function(n, obj){
                                        if(n==0){
                                            titles.push('<div style="display: table">' +
                                                '<div style="display: inline-table"><input type="checkbox" lay-filter="newseax-util-import-all" lay-skin="primary" class="layui-form-checkbox" title="全选" ></div>' +
                                                '</div>');
                                        }
                                        titles.push('<div><input type="checkbox" lay-filter="newseax-util-import-checkbox" lay-skin="primary" class="layui-form-checkbox" value="',obj,'" tid="',n,'" title="',obj,'" ></div>');
                                    });
                                    $('.newseax-util-import-title').html(titles.join(''));
                                    form.render('checkbox');
                                    form.on('checkbox(newseax-util-import-all)', function(data){
                                        var child = $('.newseax-util-import-title').find('input[type="checkbox"]');
                                        var strs = [''];
                                        child.each(function(index, item){
                                            item.checked = data.elem.checked;
                                            if(data.elem.checked && $(item).attr('tid')){
                                                if(result.tableColumns){
                                                    var str = '<div id="newseax-util-import-title-select-'+$(item).attr('tid')+'" tid="'+$(item).attr('tid')+'"><label class="layui-form-label">'+$(item).val()+'</label><div class="layui-inline"><select class="layui-select">';
                                                    $.each(result.tableColumns,function(n, obj){
                                                        str += '<option value="'+obj.columnName+'">'+obj.columnComment+'</option>';
                                                    });
                                                    str += '</select></div></div>';
                                                    strs.push(str);
                                                }
                                            }
                                        });
                                        $('.newseax-util-import-title-select').html(strs.join(''));
                                        form.render();
                                    });
                                    form.on('checkbox(newseax-util-import-checkbox)', function(data){
                                        if(result.tableColumns){
                                            if(data.elem.checked){
                                                var str = '<div id="newseax-util-import-title-select-'+$(data.elem).attr('tid')+'" tid="'+$(data.elem).attr('tid')+'"><label class="layui-form-label">'+data.value+'</label><div class="layui-inline"><select class="layui-select">';
                                                $.each(result.tableColumns,function(n, obj){
                                                    str += '<option value="'+obj.columnName+'">'+obj.columnComment+'</option>';
                                                });
                                                str += '</select></div></div>';
                                                $('.newseax-util-import-title-select').append(str);
                                                form.render('select');
                                            }else{
                                                $('#newseax-util-import-title-select-'+$(data.elem).attr('tid')).remove();
                                            }
                                        }
                                    });
                                }
                            }
                        }
                    });
                });
            });
        }
    });
}

function select2Async($select,reqUrl,textfield,valuefiled,selectData,defaultSelectedByValue,defaultSearch){
    $select.select2({
        ajax:{
            url:reqUrl,
            type:"post",
            dataType:"json",
            delay: 600,//输入时延迟查询，单位毫秒
            error:function(){//用户输入会中断请求，导致全局error弹窗
                return false;
            },
            data:function(req){//请求参数 req 为搜索框对象
                var term =  req.term ? req.term.trim():'';
                var data;
                if($.isFunction(selectData)){
                    data = selectData(term) || {};
                }else{
                    data = selectData || {};
                }
                if(term==''){
                    data[valuefiled] = defaultSelectedByValue ? defaultSelectedByValue : '';
                    term = defaultSearch ? defaultSearch : '';
                }
                data[textfield] = term;
                return data;
            },
            processResults:function(res,req){//显示结果，res 响应结果，req 请求参数（搜索框内容对象，req.term为搜索框的值）
                var option = [];
                option.push({id:"",text:"直接选择或搜索选择"});
                for(var i = 0;i<res.length;i++){
                    var op = {};
                    op.id=res[i][valuefiled];
                    op.text=res[i][textfield];
                    option.push(op)
                }
                return {results:option};//result的格式必须是[{id:'',text:''},{id:'',text:''}]
            }
        }
    });
}
var layTableOption = {
    url: ''
    ,method: 'get'
    ,id: 'id'
    ,elem: '#table'
    ,page: true
    // ,height: 'full-250'
    ,cellMinWidth: '100'
    ,request: {
        pageName: 'offset'
        ,limitName: 'limit'
    }
    ,response: {
        countName: 'total' //数据总数的字段名称，默认：count
        ,dataName: 'rows' //数据列表的字段名称，默认：data
    }
    ,cols: [[]]
    ,done: function () {
        resizeTable()
    }
    ,limits: [10,30,50,100]
    ,limit: 10
};
/**
 * 表格宽度自适应
 */

window.onresize = function () {
    resizeTable();
};

function resizeTable() {
    $(".layui-table").each(function(n, obj){
        $(obj).css("width",$(obj).parent().width());
    });
    //获取头部
    var cA = new Array();
    $(".layui-table-header").each(function (n,obj) {
        $(obj).find(".layui-table-cell").each(function (n,obj) {
            var w = $(obj).width();
            var pw = $(obj).parent().width();
            var strClass = $(obj).attr("class");
            if(strClass){
                var claArray = strClass.split(" ");
                for (var i in claArray){
                    var dataField = $(obj).parent().attr("data-field");
                    if(claArray[i].indexOf(dataField) > -1){
                        if(pw > w){
                            var cellCA = {};
                            cellCA.class = claArray[i];
                            cellCA.width = pw;
                            cA.push(cellCA);
                        }
                    }
                }
            }
        });
    });
    if(cA && cA.length > 0){
        for (var i in cA){
            $("."+cA[i].class).css("width",cA[i].width);
        }
    }
}
var unserialize = function(str){
    str = decodeURIComponent(str, true);
    var json = {};
    $.each(str.split('&'), function(n, o){
        var obj = o.split('=');
        json[obj[0]]=obj[1];
    });
    return json;
}
var ldate = function(obj, type, format, range, done, min, max){
    type = type ? type : 'date';
    format = format ? format : 'yyyy-MM-dd';
    range = range ? range : false;
    var option = {
        elem: '#'+$(obj).attr('id')
        ,type: type
        ,format: format
        ,range: range
        ,done: done
    };
    if(min) option.min = min;
    if(max) option.max = max;
    return layui.laydate.render(option);
}
var ldateParent = function(obj, type, format){
    type = type ? type : 'date';
    format = format ? format : 'yyyy-MM-dd';
    layui.laydate.render({
        elem: '#'+$(obj).attr('id')
        ,type: type
        ,format: format
    });
}
function getBrowserType() {
    var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
    var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器
    var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器
    var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
    var isOpera = userAgent.indexOf("Opera") > -1; //判断是否Opera浏览器
    var isFF = userAgent.indexOf("Firefox") > -1; //判断是否Firefox浏览器
    var isSafari = userAgent.indexOf("Safari") > -1 && userAgent.indexOf("Chrome") == -1; //判断是否Safari浏览器
    var isQQ = userAgent.indexOf("QQBrowser") > -1; //判断QQ浏览器
    var isChrome = userAgent.indexOf("Chrome") > -1 && userAgent.indexOf("Safari") > -1; //判断Chrome浏览器
    if(isIE) {
        var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
        reIE.test(userAgent);
        var fIEVersion = parseFloat(RegExp["$1"]);
        if(fIEVersion == 7) {
            return 'IE7';
        } else if(fIEVersion == 8) {
            return 'IE8';
        } else if(fIEVersion == 9) {
            return 'IE9';
        } else if(fIEVersion == 10) {
            return 'IE10';
        } else {
            return 'IE6或以下';//IE版本<=7
        }
    } else if(isEdge) {
        return 'Edge';//edge
    } else if(isIE11) {
        return 'IE11'; //IE11
    } else if(isOpera){
        return 'Opera';
    } else if(isFF){
        return 'Firefox';
    } else if(isSafari){
        return 'Safari';
    } else if(isQQ){
        return 'QQBrowser';
    } else if(isChrome){
        return 'Chrome';
    } else {
        return 'otherBrowser';
    }
}
function getCookie(name)//获取cookie
{
    if (document.cookie.length>0)
    {
        c_start=document.cookie.indexOf(name + "=");
        if (c_start!=-1)
        {
            c_start=c_start + name.length+1 ;
            c_end=document.cookie.indexOf(";",c_start);
            if (c_end==-1) c_end=document.cookie.length;
            return unescape(document.cookie.substring(c_start,c_end));
        }
    }
    return "";
}
/**
 * bootstrapTable公共配置
 * @type {{url: string, method: string, toolbar: string, striped: boolean, cache: boolean, pagination: boolean, sortable: boolean, sortOrder: string, queryParams: string, sidePagination: string, pageNumber: number, pageSize: number, pageList: number[], search: boolean, strictSearch: boolean, showColumns: boolean, showRefresh: boolean, iconSize: string, minimumCountColumns: number, clickToSelect: boolean, height: number, uniqueId: string, showToggle: boolean, cardView: boolean, detailView: boolean}}
 */
var bootstrapTableOption={
    url: '',           //请求后台的URL（*）
    method: 'get',                                  //请求方式（*）
    toolbar: '#toolbar',                          //工具按钮用哪个容器
    striped: true,                                  //是否显示行间隔色
    cache: false,                                   //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
    pagination: true,                               //是否显示分页（*）
    sortable: false,                                //是否启用排序
    sortOrder: "asc",                               //排序方式
    queryParams: '',               //传递参数（*）
    sidePagination: "server",                       //分页方式：client客户端分页，server服务端分页（*）
    pageNumber:1,                                   //初始化加载第一页，默认第一页
    pageSize: 10,                                   //每页的记录行数（*）
    pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
    search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
    strictSearch: true,
    showColumns: true,                  //是否显示所有的列
    showRefresh: true,                  //是否显示刷新按钮
    iconSize: 'outline',
    minimumCountColumns: 2,             //最少允许的列数
    clickToSelect: true,                //是否启用点击选中行
    height: 600,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
    classes: 'table table-hover',
    uniqueId: "",                     //每一行的唯一标识，一般为主键列
    showToggle:true,                    //是否显示详细视图和列表视图的切换按钮
    cardView: false,                    //是否显示详细视图
    detailView: false,                   //是否显示父子表
    responseHandler: function(result){//转换表情
        // data = JSON.parse(emoji(JSON.stringify(data)));
        return result.data;
        //return data;
    },
    onLoadSuccess: function(data){
        $(".fixed-table-container").css({
            "height": $("body").height()-200-$(".ibox-title").height()-$(".search").height()-$("#toolbar").height()
        });
    }
};
function emoji(str){
    return twemoji.parse(str, function(icon, options, variant){
        return 'plugin/twemoji/16x16/'+icon+options.ext;
    });
}
/**
 * 表单转json对象
 * @returns {{}}
 */
$.fn.serializeObject = function() {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};
/**
 * 表单转json字符串
 * @returns {string}
 */
$.fn.serializeJsonString = function() {
    var o = this.serializeObject();
    return JSON.stringify(o);
};

/**
 * 加载layui下拉选
 * @param selector
 * @param url
 * @param text
 * @param value
 * @param defaultValue
 * @param afterFunc
 */
function loadLaySelect(selector,url,text,value,defaultValue,afterFunc) {
    var $selected = $(selector);
    $selected.empty();
    $selected.AddOption("请选择","",true,0);
    $.ajax({
        url: url,
        type:"GET",
        success:function(result){
            if(result && result.length > 0) {
                for(var i = 0;i< result.length ;i++) {
                    var currValue = result[i][value];
                    var selected = defaultValue?  defaultValue == currValue : false;
                    $selected.AddOption(result[i][text], currValue,selected,i+1)
                }
                if(layui && layui.form) {
                    layui.form.render('select');
                }
                if ($.isFunction(afterFunc)){
                    afterFunc();
                }
            }
        }
    });
}

/**
 * 复制select控件option项到另一个select控件
 */
function selectOptionCopy(sourceCtlId,targetCtlId,selected){
    $("#"+targetCtlId).empty();
    $("#"+sourceCtlId+" option").each(function () {
        var oValue = $(this).val().toString();
        var oText = $(this).text().toString();
        var option = $("<option>").val(oValue).text(oText);
        if (selected && oValue == selected) {
            option.attr("selected",true);
        }
        $("#"+targetCtlId).append(option);
    });
}
/**
 * 复制select控件option项到另一个select控件
 */
function layuiSelectOptionCopy(sourceCtlId,targetCtlId,selected){
    selectOptionCopy(sourceCtlId,targetCtlId,selected);
    if(layui && layui.form) {
        layui.form.render('select');
    }
}
function loadLabelData(data) {
    var obj =data;
    var key,value,tagName,type;
    for(var x in obj){
        key = x;
        value = obj[x];
        $("[name='"+key+"'],[name='"+key+"[]']").each(function(){
            tagName = $(this)[0].tagName;
            type = $(this).attr('type');
            if(tagName=='LABEL'){
                $(this).html(value);
            }else if(tagName=='IMG'){
                $(this).attr("src", value);
            }else if(tagName=='SELECT'){
                $(this).val(value);
            }else if(tagName=='INPUT'){
                if(type=='hidden'){
                    $(this).val(value);
                }
            }
        });
    }
}
/**
 * 根据指定类型标签的指定属性的值与json对象key值对应
 * 填充Html
 * @param jsonStr json格式数据
 * @param elmType 标签类型
 * @param attrName 属性名称，缺省值name
 */
function loadHtml(jsonStr,elmType,attrName){
    var obj =jsonStr;
    attrName = attrName || "name";
    for(var x in obj){
        var $elm = $(elmType + "["+attrName+"=" + x + "]");
        if($elm){
            $elm.html(obj[x])
        }
    }
}/**
 * 格式化输出json字符串
 * 根据指定类型标签的指定属性的值与json对象key值对应
 * 填充Html
 * @param jsonStr json格式数据
 * @param elmType 标签类型
 * @param attrName 属性名称，缺省值name
 */
function loadHtmlJsonFormat(jsonStr,elmType,attrName){
    var obj =jsonStr;
    var undef;
    attrName = attrName || "name";
    for(var x in obj){
        var $elm = $(elmType + "["+attrName+"=" + x + "]");
        if($elm){
            var $pre;
            if ($elm.is('pre')){
                $pre = $elm;
            }else {
                $elm.html("<pre></pre>");
                $pre = $elm.find("pre");
            }
            var jsonObj;
            if (obj[x] && typeof  obj[x] === "string"){
                try {
                    jsonObj = JSON.parse(obj[x]);
                }catch(e){
                    jsonObj = obj[x] || undef;
                }
            }else {
                jsonObj = obj[x]  || undef;
            }
            $pre.html(JSON.stringify(jsonObj,null,"   "))
        }
    }
}

/*
 参数解释：
 title	标题
 contentDivId		内容DIV的ID
 w		            弹出层宽度（缺省调默认值）
 h		            弹出层高度（缺省调默认值）
 */
function showLayer(title,contentDivId,w,h){
    if (title == null || title == '') {
        title=false;
    }
    if (w == null || w == '') {
        w=800;
    }
    if (h == null || h == '') {
        h=($(window).height() - 50);
    }
    layer.open({
        type: 1,//页面层
        maxmin: true,
        area: [w+'px', h +'px'],
        title: title,
        content: $layui("#"+contentDivId)
    });
}

/*
 参数解释：
 title	标题
 url		请求的url
 id		需要操作的数据id
 w		弹出层宽度（缺省调默认值）
 h		弹出层高度（缺省调默认值）
 */
function layerShowPage(title,url,w,h){
    if (title == null || title == '') {
        title=false;
    }
    if (w == null || w == '') {
        w=800;
    }
    if (h == null || h == '') {
        h=($(window).height() - 50);
    }
    layer.open({
        type: 2,
        area: [w+'px', h +'px'],
        fix: false, //不固定
        maxmin: true,
        scrollbar: false,//屏蔽游览器滚动条
        shade:0.4,
        title: title,
        content: url
    });
}

/**
 * 格式化文件大小
 * @param limit
 * @returns {*}
 */
function formatFileLenth(limit){
    var size = "";
    if(limit < 0.1 * 1024){                            //小于0.1KB，则转化成B
        size = limit.toFixed(2) + "B"
    }else if(limit < 0.1 * 1024 * 1024){            //小于0.1MB，则转化成KB
        size = (limit/1024).toFixed(2) + "KB"
    }else if(limit < 0.1 * 1024 * 1024 * 1024){        //小于0.1GB，则转化成MB
        size = (limit/(1024 * 1024)).toFixed(2) + "MB"
    }else{                                            //其他转化成GB
        size = (limit/(1024 * 1024 * 1024)).toFixed(2) + "GB"
    }

    var sizeStr = size + "";                        //转成字符串
    var index = sizeStr.indexOf(".");                    //获取小数点处的索引
    var dou = sizeStr.substr(index + 1 ,2)            //获取小数点后两位的值
    if(dou == "00"){                                //判断后两位是否为00，如果是则删除00
        return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
    }
    return size;
}